import { createSlice } from "@reduxjs/toolkit";
//用户相关store
const userStore = createSlice({
    name: 'user',
    // 初始数据
    // initialState: {
    // token: null,//用户token
    // isLogged: false,//是否登录
    // user: null//用户信息

    // },
    initialState: () => {
        const token = localStorage.getItem('token')
        const user = JSON.parse(localStorage.getItem('user'))
        const expirationTime = +localStorage.getItem('expirationTime')
        if (token) {//本地有数据
            return {
                token: token,
                user: user,
                isLogged: true,
                expirationTime: expirationTime//登录失效时间
            }
        } else {//本地没有数据
            return {
                token: null,//用户token
                isLogged: false,//是否登录
                user: null,//用户信息
                expirationTime: 0//登录失效时间
            }
        }



    },
    // 修改数据的同步方法,支持直接修改
    reducers: {
        //登录时保存数据
        login(state, action) {
            state.isLogged = true
            state.token = action.payload.token
            state.user = action.payload.user
            //获取当前时间戳
            const currentTime = Date.now()
            //设置登录有效时间
            const timeOut = 1000 * 60 * 60 * 24 * 7//一周
            state.expirationTime = currentTime + timeOut//设置失效日期
            //存储到本地
            localStorage.setItem('token', state.token)
            localStorage.setItem('user', JSON.stringify(state.user))
            localStorage.setItem('expirationTime',state.expirationTime+"")


        },
        //退出登录时清空数据
        logout(state, action) {
            state.isLogged = false
            state.token = ''
            state.user = null
            //移除本地存储数据
            localStorage.removeItem('token')
            localStorage.removeItem('user')
            localStorage.removeItem('expirationTime')
        },

    }
})
export default userStore
export const { login, logout } = userStore.actions